# coding=utf-8

import sys
import pickle
import pprint

choise = sys.argv[1]
if choise == "r":
	category = sys.argv[2]
	item = sys.argv[3]

'''
密码管理器

* 保存密码
* 获取密码

格式：
* password
* title

{"title": "passwd"}

zpass.py w  写密码
zpass.py r web jingfeng 读密码

分类：
* web
* 服务器

格式：
{
    "web":{
        "title":
            {
                "user":"test",
                "passwwd": "123456",
                "url": "jingfeng.com"
            }, 
        "zhihu":
            {
                "user":"test",
                "passwd":"123456"
                "url":"zhihu.com"
            }
}

'''


def read_data():
	try:
		with open("zpass.pass", "rb") as f:
			return pickle.load(f)
	except IOError as e:
		return False
	except Exception as e:
		raise e


def write_data(data):
	try:
		with open("zpass.pass", "wb") as f:
			pickle.dump(data, f)
			return True
	except IOError as e:
		return False
	except Exception as e:
		raise e


class Password(dict):

	def __init__(self, category, title, user, passwd):
		super().__init__()
		self.category = category
		self.title = title
		self[title] = {"user":user, "passwd":passwd}

	def save_passwd(self):
		data_pass = read_data() if read_data() else {}
		data_pass[self.category] = self
		pprint.pprint(data_pass)
		insert_status = write_data(data_pass)
		if not insert_status:
			print("保存失败！")
		print("保存成功！")
		return True
        
	@staticmethod
	def get_passwd():
		obj = read_data()
		return obj[category][item]

	@classmethod
	def get_item(cls):
		return ("title", "user", "passwd")



class WebPassword(Password):
	def __init__(self, category, title, user, passwd, url):
		super().__init__(category, title, user, passwd)
		self[title]["url"] = url

	@classmethod
	def get_item(cls):
		return ("title", "user", "passwd", "url")


def main():
	if choise == "r":
		print(Password.get_passwd())
	if choise == "w":
		user_choice = input("1 web, 2 server, 0 退出 : ")
		data = {}
		if user_choice == "1":
			temp = WebPassword.get_item()
			print(temp)
			for i in temp:
				data[i] = input(i+" :")
			print(data)
			method = WebPassword(category="web", **data)
			method.save_passwd()
		elif user_choice == "2":
			pass
		else:
			print("退出")


if __name__ == "__main__":
	main()